local last_hp_ratio = 0;
local last_hp = 0;
local last_mp_ratio = 0;
local last_skill_ratio = 0;

--------- <LoadSettings> ---------
function EN_LoadSettings()
	SaveVariables("ENSettings");
	
	local ENList = {
			["HPWarning"] = {
				["Ratio"] = 0.5,
				["SoundFile"] = "Interface/Addons/EventNotify/Sound/hp.wav",
				["UseMessage"] = true,
				["UseSound"] = true,
				["Description"] = "EN: Low Hp Warning",
			},
			["Ab1Warning"] = {
				["Ratio"] = 0.5,
				["SoundFile"] = "Interface/Addons/EventNotify/Sound/ab1.wav",
				["UseMessage"] = true,
				["UseSound"] = true,
				["Description"] = "EN: Low Skill Ability1 / Mana Warning",				
			},
			["Ab2Warning"] = {
				["Ratio"] = 0.5,
				["SoundFile"] = "Interface/Addons/EventNotify/Sound/ab2.wav",
				["UseMessage"] = true,
				["UseSound"] = true,
				["Description"] = "EN: Low Skill Ability2 / Mana Warning",				
			},
			["HardHitWarning"] = {
				["Ratio"] = 0.33,
				["SoundFile"] = "Interface/Addons/EventNotify/Sound/hardhit.wav",
				["UseMessage"] = true,
				["UseSound"] = true,
				["Description"] = "EN: Hard Hit Warning",
			},
			["Version"] = {
				["Number"] = 0.26,
			},
			["MsgRedirection"] = {
				["UseRedir"] = false,
				["Description"] = "EN: Redirect EN Messages",
			},
			["NewMail"] = {
				["SoundFile"] = "Interface/Addons/EventNotify/Sound/newmail.wav",
				["UseMessage"] = true,
				["UseSound"] = true,
				["Description"] = "EN: New Mail",				
			},
			["FriendOnline"] = {
				["SoundFile"] = "Interface/Addons/EventNotify/Sound/friendonline.wav",
				["UseMessage"] = true,
				["UseSound"] = true,
				["Description"] = "EN: Friend Online",				
			},
			["WhisperReceive"] = {
				["SoundFile"] = "Interface/Addons/EventNotify/Sound/whisperreceive.wav",
				["UseMessage"] = false,
				["UseSound"] = true,
				["Description"] = "EN: Whisper Receive",				
			},
			["QuestComplete"] = {
				["SoundFile"] = "Interface/Addons/EventNotify/Sound/questcomplete.wav",
				["UseMessage"] = false,
				["UseSound"] = true,
				["Description"] = "EN: Quest Complete",				
			},
			["QuestFinished"] = {
				["SoundFile"] = "Interface/Addons/EventNotify/Sound/questfinished.wav",
				["UseMessage"] = true,
				["UseSound"] = true,
				["Description"] = "EN: Quest Finished",				
			},
			["WarningMessage"] = {
				["SoundFile"] = "sound/interface/ui_sysmsg_warning.mp3",
				["UseMessage"] = true,
				["UseSound"] = true,
				["Description"] = "EN: Default Game WarningMessage",				
			},
			["SystemMessage"] = {
				["SoundFile"] = "sound/interface/ui_sysmsg_normal.mp3",
				["UseMessage"] = true,
				["UseSound"] = true,
				["Description"] = "EN: Default Game SystemMessage",				
			},
			["FramePos"] = {
				["CFGPosX"] = 100,
				["CFGPosY"] = 100,
				["RedirPosX"] = 100,
				["RedirPosY"] = 100,
			}
		};
	
    -- There we go --
	EN_VAR = getglobal("CharacterSelectCharacterButton"..CHARACTER_SELECT.selectedIndex.."ButtonTextName"):GetText();
	
	if (ENSettings == nil) then 
		ENSettings = {};
	end
	if (ENSettings[EN_VAR] == nil) then 
		ENSettings[EN_VAR] = {};
	end
    if (ENSettings[EN_VAR]["Version"] == nil) then
		ENSettings[EN_VAR] = ENList;
		DEFAULT_CHAT_FRAME:AddMessage(">>> EventNotify Addon Defaults loaded!");
	elseif (ENSettings[EN_VAR]["Version"] and (ENSettings[EN_VAR]["Version"]["Number"] < 0.26)) then
		ENSettings[EN_VAR] = ENList;
		DEFAULT_CHAT_FRAME:AddMessage(">>> EventNotify Addon Updated and Defaults loaded!");
	else
		for l,m in pairs(ENList) do
			if (ENSettings[EN_VAR][l] == nil) then
				ENSettings[EN_VAR][l] = m;
			end
		end
		DEFAULT_CHAT_FRAME:AddMessage(">>> EventNotify Addon v."..ENSettings[EN_VAR]["Version"]["Number"].." loaded! Use '/EventNotify' to open & close config frame.");
	end
	
	EN_Position("CFG",EventNotify_ConfigFrame);
	EN_Position("Redir",EventNotify_MessageFrame);
	EN_Locale();
	EN_RegAM();
	
	if (ENSettings[EN_VAR]["MsgRedirection"]["UseRedir"] == true) then
		EventNotify_MessageFrame:Show();
	end
		
	SaveVariables("ENSettings");
end

function EN_RegAM()
	if AddonManager then
			local addon = {
				name = "EventNotify",
				version = "v0.26",
				author = "F636y623",
				description = "Plays sounds & shows messages on different ingame events / occasions.\nUse '/EventNotify' or click button to open & close config window.",
				category = "Other",
				configFrame = EventNotify_ConfigFrame, 
				slashCommand = "/EventNotify",
			}
			if AddonManager.RegisterAddonTable then
				AddonManager.RegisterAddonTable(addon)
			else
				AddonManager.RegisterAddon(addon.name, addon.description, addon.icon, addon.category, 
					addon.configFrame, addon.slashCommand, addon.miniButton, addon.version, addon.author)
			end
		
		end
end

function EN_Position(posvar,this)
    this:ClearAllAnchors();
    if (ENSettings[EN_VAR]["FramePos"][posvar.."PosX"] == nil or ENSettings[EN_VAR]["FramePos"][posvar.."PosY"] == nil) then
		this:SetAnchor("CENTER", "CENTER", "UIParent", 0, 0); 
	else
	   local scale = GetUIScale();
	   this:SetAnchor("TOPLEFT", "TOPLEFT", "UIParent", ENSettings[EN_VAR]["FramePos"][posvar.."PosX"] / scale, ENSettings[EN_VAR]["FramePos"][posvar.."PosY"] / scale);   
    end  
end

function EN_SavePos(posvar,this)
	ENSettings[EN_VAR]["FramePos"][posvar.."PosX"], ENSettings[EN_VAR]["FramePos"][posvar.."PosY"] = this:GetPos();
end

--------- <LocaleSettings> ---------
function EN_Locale()
	local ENClientLocale = GetLocation();
	if not(ENClientLocale == "DE" or ENClientLocale =="ENEU" or ENClientLocale =="ENUS") then
		ENClientLocale = "ENEU";
		DEFAULT_CHAT_FRAME:AddMessage(">> EN: Your clients language isn't supported! Default ENEU locale loaded!");
	end
	dofile("Interface/Addons/EventNotify/Locales/"..ENClientLocale..".lua");
end

--------- <OnEvent> ---------
function EN_OnEvent(event, this)
	if (event == "VARIABLES_LOADED") then
		EN_LoadSettings();
	elseif (event == "UNIT_HEALTH" and arg1 == "player") then 
		EN_Health(); 
	elseif (event == "UNIT_MANA" and arg1 == "player") then 
		EN_Mana(); 
	elseif (event == "UNIT_SKILL" and arg1 == "player") then 
		EN_Skill(); 
	elseif (event == "CHAT_MSG_SYSTEM" or "ONLINE_FRIEND" or "CHAT_MSG_WHISPER" or "QUEST_COMPLETE") then 
		EN_Custom(event,this); 
	elseif (event == "SYSTEM_MESSAGE") then
		SendSystemMsg(arg1);
	elseif (event == "WARNING_MESSAGE") then
		SendWarningMsg(arg1);
	end
end

--------- <Health, Mana, Skill> ---------
function EN_Health()
	local ratiohp = UnitHealth("player")/UnitMaxHealth("player");
	
	if (ratiohp < ENSettings[EN_VAR]["HPWarning"]["Ratio"]) and (last_hp_ratio >= ENSettings[EN_VAR]["HPWarning"]["Ratio"]) then
        if (ENSettings[EN_VAR]["HPWarning"]["UseMessage"] == true) then
			SendENMsg(ENLocales["String"]["HPDispMsg"]);
		end	
		if (ENSettings[EN_VAR]["HPWarning"]["UseSound"] == true) then
			PlaySoundByPath(ENSettings[EN_VAR]["HPWarning"]["SoundFile"]);
		end
    end
	
	last_hp_ratio = ratiohp;
	
	local curr_hp = UnitHealth("player");
	local curr_hp_max = UnitMaxHealth("player");
	
	
	if (((last_hp - curr_hp) > (ENSettings[EN_VAR]["HardHitWarning"]["Ratio"] * curr_hp_max)) and (last_hp > curr_hp)) then
        if (ENSettings[EN_VAR]["HardHitWarning"]["UseMessage"] == true) then
			SendENMsg(ENLocales["String"]["HardHitDispMsg"]);
		end	
		if (ENSettings[EN_VAR]["HardHitWarning"]["UseSound"] == true) then
			PlaySoundByPath(ENSettings[EN_VAR]["HardHitWarning"]["SoundFile"]);
		end
    end
	
	last_hp = UnitHealth("player");
end	

function EN_Mana()
	local ratiomp = UnitMana("player")/UnitMaxMana("player");
	
	if (ratiomp < ENSettings[EN_VAR]["Ab1Warning"]["Ratio"]) and (last_mp_ratio >= ENSettings[EN_VAR]["Ab1Warning"]["Ratio"]) then
        if (ENSettings[EN_VAR]["Ab1Warning"]["UseMessage"] == true) then
			if (UnitMaxMana("player") <= 100) then
				SendENMsg(ENLocales["String"]["Skill1DispMsg"]);
			else
				SendENMsg(ENLocales["String"]["ManaDispMsg"]);
			end
		end		
		if (ENSettings[EN_VAR]["Ab1Warning"]["UseSound"] == true) then
			if (UnitMaxMana("player") <= 100) then
				PlaySoundByPath(ENSettings[EN_VAR]["Ab2Warning"]["SoundFile"]);
			else
				PlaySoundByPath(ENSettings[EN_VAR]["Ab1Warning"]["SoundFile"]);
			end
		end	
    end
	
	last_mp_ratio = ratiomp;
end

function EN_Skill()
	local ratioskill = UnitSkill("player")/UnitMaxSkill("player");
	
	if (ratioskill < ENSettings[EN_VAR]["Ab2Warning"]["Ratio"]) and (last_skill_ratio >= ENSettings[EN_VAR]["Ab2Warning"]["Ratio"]) then
        if (ENSettings[EN_VAR]["Ab2Warning"]["UseMessage"] == true) then
			if (UnitMaxSkill("player") > 100) then
				SendENMsg(ENLocales["String"]["ManaDispMsg"]);
			else
				SendENMsg(ENLocales["String"]["Skill2DispMsg"]);
			end
		end	
		if (ENSettings[EN_VAR]["Ab2Warning"]["UseSound"] == true) then
			if (UnitMaxSkill("player") > 100) then
				PlaySoundByPath(ENSettings[EN_VAR]["Ab1Warning"]["SoundFile"]);
			else
				PlaySoundByPath(ENSettings[EN_VAR]["Ab2Warning"]["SoundFile"]);
			end
		end	
    end
	
	last_skill_ratio = ratioskill;
end

--------- <Custom Events> ---------
function EN_Custom(event,this)

local event = event;
	if (event == "CHAT_MSG_SYSTEM" and arg1 == ENLocales["String"]["NewMailChat"]) then
		if (ENSettings[EN_VAR]["NewMail"]["UseMessage"] == true) then
			SendENMsg(ENLocales["String"]["NewMailDispMsg"]);
		end
		if (ENSettings[EN_VAR]["NewMail"]["UseSound"] == true) then
			PlaySoundByPath(ENSettings[EN_VAR]["NewMail"]["SoundFile"]);
		end
	elseif (event == "ONLINE_FRIEND") then
		if (ENSettings[EN_VAR]["FriendOnline"]["UseMessage"] == true) then
			SendENMsg(ENLocales["String"]["FriendOnlineDispMsg"]);
		end
		if (ENSettings[EN_VAR]["FriendOnline"]["UseSound"] == true) then
			PlaySoundByPath(ENSettings[EN_VAR]["FriendOnline"]["SoundFile"]);
		end
	elseif (event == "CHAT_MSG_WHISPER") then
		if (ENSettings[EN_VAR]["WhisperReceive"]["UseMessage"] == true) then
			SendENMsg(ENLocales["String"]["WhisperReceiveDispMsg"]);
		end
		if (ENSettings[EN_VAR]["WhisperReceive"]["UseSound"] == true) then
			PlaySoundByPath(ENSettings[EN_VAR]["WhisperReceive"]["SoundFile"]);
		end
	elseif (event == "QUEST_COMPLETE") then
		if (ENSettings[EN_VAR]["QuestComplete"]["UseMessage"] == true) then
			SendENMsg(ENLocales["String"]["QuestCompleteDispMsg"]);
		end
		if (ENSettings[EN_VAR]["QuestComplete"]["UseSound"] == true) then
			PlaySoundByPath(ENSettings[EN_VAR]["QuestComplete"]["SoundFile"]);
		end
	elseif (event == "CHAT_MSG_SYSTEM" and (string.find(arg1,ENLocales["String"]["QuestFinishedChat"]) ~= nil)) then
		if (ENSettings[EN_VAR]["QuestFinished"]["UseMessage"] == true) then
			SendENMsg(ENLocales["String"]["QuestFinishedDispMsg"]);
		end
		if (ENSettings[EN_VAR]["QuestFinished"]["UseSound"] == true) then
			PlaySoundByPath(ENSettings[EN_VAR]["QuestFinished"]["SoundFile"]);
		end
	end
end

function SendWarningMsg(text)
	if (ENSettings[EN_VAR]["WarningMessage"]["UseSound"] == true) then
		PlaySoundByPath(ENSettings[EN_VAR]["WarningMessage"]["SoundFile"]);
	end
	if (ENSettings[EN_VAR]["WarningMessage"]["UseMessage"] == true) then
		if (ENSettings[EN_VAR]["MsgRedirection"]["UseRedir"] == true) then
			SendENMsg(text);
		elseif (ENSettings[EN_VAR]["MsgRedirection"]["UseRedir"] == false) then
			WarningFrame:AddMessage(text, 0.93, 0.11, 0.14);
		end
	end
end

function SendSystemMsg(text)
	if (ENSettings[EN_VAR]["SystemMessage"]["UseSound"] == true) then
		PlaySoundByPath(ENSettings[EN_VAR]["SystemMessage"]["SoundFile"]);
	end	
	if (ENSettings[EN_VAR]["SystemMessage"]["UseMessage"] == true) then
		if (ENSettings[EN_VAR]["MsgRedirection"]["UseRedir"] == true) then
			SendENMsg(text);
		elseif (ENSettings[EN_VAR]["MsgRedirection"]["UseRedir"] == false) then
			SystemMsgFrame:AddMessage(text, 1, 0.95, 0.40);
		end
	end
end

function SendENMsg(text)
	if (ENSettings[EN_VAR]["SystemMessage"]["UseMessage"] == true) then
		if (ENSettings[EN_VAR]["MsgRedirection"]["UseRedir"] == true) then
			EventNotify_MessageFrame:AddMessage(text, 0, 1, 0);
		elseif (ENSettings[EN_VAR]["MsgRedirection"]["UseRedir"] == false) then
			SystemMsgFrame:AddMessage(text, 1, 0.95, 0.40);
		end
	end	
end

function EN_AddGT(text,this)
	GameTooltip:SetOwner(this, "ANCHOR_BOTTOMRIGHT");
	GameTooltip:SetText(text, 1.0, 1.0, 1.0);
	GameTooltip:Show();
end

--------- <DropDownFunctions> ---------
function EN_DropDownShow()
	UIDropDownMenu_AddButton({["text"] = "-- Events --"});
	for l, m in pairs(ENSettings[EN_VAR]) do
		if not((l == "Version") or (l == "FramePos") or (l == "MsgRedirection")) then
			UIDropDownMenu_AddButton({["text"] = l, ["func"] = EN_DropDownClick});
		end
	end
	UIDropDownMenu_AddButton({["text"] = "-- EN Frame --"});
	UIDropDownMenu_AddButton({["text"] = "MsgRedirection", ["func"] = EN_DropDownClick});
end

function EN_DropDownClick(button)
		UIDropDownMenu_SetSelectedID(EventNotify_DropDown, button:GetID());
		selectedButtonText = button:GetText();
		EventNotify_SelectedText:SetText(ENSettings[EN_VAR][selectedButtonText]["Description"]);
		
		if (ENSettings[EN_VAR][selectedButtonText]["UseSound"]) then
			if (ENSettings[EN_VAR][selectedButtonText]["UseSound"] == true) then
				EventNotify_Check1:SetChecked(true);
			elseif (ENSettings[EN_VAR][selectedButtonText]["UseSound"] == false) then
				EventNotify_Check1:SetChecked(false);
			end
		end
		
		if (ENSettings[EN_VAR][selectedButtonText]["UseMessage"]) then
			if (ENSettings[EN_VAR][selectedButtonText]["UseMessage"] == true) then
				EventNotify_Check2:SetChecked(true);
			elseif (ENSettings[EN_VAR][selectedButtonText]["UseMessage"] == false) then
				EventNotify_Check2:SetChecked(false);
			end
		end
		
		if (ENSettings[EN_VAR][selectedButtonText]["UseRedir"]) then
			if (ENSettings[EN_VAR][selectedButtonText]["UseRedir"] == true) then
				EventNotify_Check3:SetChecked(true);
			elseif (ENSettings[EN_VAR][selectedButtonText]["UseRedir"] == false) then
				EventNotify_Check3:SetChecked(false);
			end
		end
		
		if(selectedButtonText == "HPWarning" or selectedButtonText == "Ab1Warning" or selectedButtonText == "Ab2Warning" or selectedButtonText == "HardHitWarning") then
			EventNotify_Check1:Show();
			EventNotify_Check2:Show();
			EventNotify_Check3:Hide();
			EventNotify_RatioBox:SetText(ENSettings[EN_VAR][selectedButtonText]["Ratio"]);
			EventNotify_RatioBox:Show();
			EventNotify_RatioBox:Enable();		
		elseif(selectedButtonText == "MsgRedirection") then
			EventNotify_Check1:Hide();
			EventNotify_Check2:Hide();
			EventNotify_Check3:Show();
			EventNotify_RatioBox:SetText("");
			EventNotify_RatioBox:Disable();
			EventNotify_RatioBox:Hide();
		else	
			EventNotify_Check1:Show();
			EventNotify_Check2:Show();
			EventNotify_Check3:Hide();
			EventNotify_RatioBox:SetText("");
			EventNotify_RatioBox:Disable();
			EventNotify_RatioBox:Hide();			
		end
end

function EN_Check1Click()
	if (EventNotify_Check1:IsChecked() == true) then 
		ENSettings[EN_VAR][selectedButtonText]["UseSound"] = true;
		DEFAULT_CHAT_FRAME:AddMessage(">> "..ENSettings[EN_VAR][selectedButtonText]["Description"].." Sound ON");
	elseif (EventNotify_Check1:IsChecked() == false) then
			ENSettings[EN_VAR][selectedButtonText]["UseSound"] = false;
			DEFAULT_CHAT_FRAME:AddMessage(">> "..ENSettings[EN_VAR][selectedButtonText]["Description"].." Sound OFF");
	end
	
	SaveVariables("ENSettings");
end

function EN_Check2Click()
	if (EventNotify_Check2:IsChecked() == true) then 
		ENSettings[EN_VAR][selectedButtonText]["UseMessage"] = true;
		DEFAULT_CHAT_FRAME:AddMessage(">> "..ENSettings[EN_VAR][selectedButtonText]["Description"].." Message ON");
	elseif (EventNotify_Check2:IsChecked() == false) then
			ENSettings[EN_VAR][selectedButtonText]["UseMessage"] = false;
			DEFAULT_CHAT_FRAME:AddMessage(">> "..ENSettings[EN_VAR][selectedButtonText]["Description"].." Message OFF");
	end
	
	SaveVariables("ENSettings");
end

function EN_Check3Click()
	if (EventNotify_Check3:IsChecked() == true) then 
		ENSettings[EN_VAR][selectedButtonText]["UseRedir"] = true;
		DEFAULT_CHAT_FRAME:AddMessage(">> "..ENSettings[EN_VAR][selectedButtonText]["Description"].." Redirection ON");
		EventNotify_MessageFrame:Show();
	elseif (EventNotify_Check3:IsChecked() == false) then
			ENSettings[EN_VAR][selectedButtonText]["UseRedir"] = false;
			DEFAULT_CHAT_FRAME:AddMessage(">> "..ENSettings[EN_VAR][selectedButtonText]["Description"].." Redirection OFF");
			EventNotify_MessageFrame:Hide();
	end
	
	SaveVariables("ENSettings");
end

function EN_RatioBoxEnter()

	local theRatio = EventNotify_RatioBox:GetNumber();
	if ((theRatio <= 0) or (theRatio >= 1)) then
		ENSettings[EN_VAR][selectedButtonText]["Ratio"] = 0.5;
		DEFAULT_CHAT_FRAME:AddMessage(">> EN: Specified Ratio invalid, must be > 0 and < 1. Ratio set to default value 0.5");
	else
		ENSettings[EN_VAR][selectedButtonText]["Ratio"] = theRatio;
		DEFAULT_CHAT_FRAME:AddMessage(">> "..ENSettings[EN_VAR][selectedButtonText]["Description"].." Ratio set to "..theRatio);
	end
	
	SaveVariables("ENSettings");
end

--------- <GetCommandParameters> ---------
function GetWords(str)
	local ret = {};
	local pos = 0;
	while(true) do
		local word;
		_, pos, word = string.find(str, "^ *([^%s]+) *", pos+1);
		if(not word) then
			return ret;
		end
		table.insert(ret, word);
	end
end

--------- <SlashControl> ---------
function ENSlashControl(ebox, var)
	local var = string.lower(var);
	local liste = GetWords(var);
	
	if liste[1] ~= nil then
		DEFAULT_CHAT_FRAME:AddMessage(">> EN: Use '/EventNotify' to open & close the config window.");
	else
		if (EventNotify_ConfigFrame:IsVisible() == true) then
			EventNotify_ConfigFrame:Hide();
		elseif (EventNotify_ConfigFrame:IsVisible() == false) then
			EventNotify_ConfigFrame:Show();
		end
	end
	
	SaveVariables("ENSettings");
end

SLASH_ENSlashControl1 = "/EventNotify";
SlashCmdList["ENSlashControl"] = ENSlashControl;
